import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {SystemService} from "../system.service";
import {StorageService} from "../../services/storage.service";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {ConfirmationService} from "primeng/primeng";
import {DomSanitizer} from "@angular/platform-browser";
import {
  dateValidator, emailValidator, idcardValidator, nameValidator, nullValidator, phoneValidator,
  pidValidator
} from "../../validator/validators";
import {PUblicMethod} from "../../services/PUblicMethod";
@Component({
  selector: 'app-person-edit',
  templateUrl: './person-edit.component.html',
  styleUrls: ['./person-edit.component.css']
})
export class PersonEditComponent implements OnInit {
  imgUrl_1;//图片一预览base64
  imgUrl_2;//图片二预览base64
  display;
  title;
  showAddPlanMask: boolean = false;          //添加弹出框
  @Output() closePersonEdit =new EventEmitter();
  @Output() addPer = new EventEmitter(); //新增人员
  @Output() updatePer = new EventEmitter(); //修改人员
  @Input() currentPer;
  @Input() state;
  person: FormGroup;
  maxDate: Date;//注册日期的最大值，今天
  minDate: Date;//失效日期的最小值，今天
  registedate;
  uploadedFiles: any[] = [];
  submitAddPerson = [//新增人员参数
    {
      "pid": '',
      "oid": '',
      "name": '',
      "pwd": '',
      "sex": '',
      "birthday": '',
      "registedate": '',
      "validdate": '',
      "organization": '',
      "post": '',
      "tel": '',
      "mobile": '',
      "addr": '',
      "email": '',
      "idcard": '',
      "license": '',
      "wechat": '',
      "photo1": '',
      "photo2": '',
      "remark1": '',
      "remark2": '',
      "remark3": '',
      "remark4": ''
    }
  ];
  submitUpdatePerson = [//修改人员参数
    {
      "pid": '',
      "oid": '',
      "name": '',
      "sex": '',
      "birthday": '',
      "registedate": '',
      "validdate": '',
      "organization": '',
      "post": '',
      "tel": '',
      "mobile": '',
      "addr": '',
      "email": '',
      "idcard": '',
      "license": '',
      "wechat": '',
      "photo1": '',
      "photo2": '',
      "remark1": '',
      "remark2": '',
      "remark3": '',
      "remark4": ''
    }
  ];

  constructor(
    private systemService: SystemService,
    private storageService: StorageService,
    private fb: FormBuilder,
    private confirmationService: ConfirmationService,
    private sanitizer: DomSanitizer
  ) {
    this.person = fb.group({
        perName: ['', [Validators.required, nameValidator]],
        pid: ['', [Validators.required, pidValidator]],
        oid: [''],
        pwd: ['', [Validators.required, Validators.minLength(6), Validators.maxLength(18), nullValidator]],
        sex: [''],
        idcard: ['', idcardValidator],
        license: [''],
        birthday: [''],
        dateGroup: fb.group({
          registedate: [''],
          validdate: [''],
        }, {validator: dateValidator}),
        /*registedate: [''],
        validdate: [''],*/
        addr: [''],
        organization: ['', Validators.required],
        post: [''],
        mobile: ['', [Validators.required, phoneValidator]],
        tel: ['', phoneValidator],
        email: ['', emailValidator],
        wechat: [''],
        photo1: [''],
        photo2: [''],
        remark1: ['', Validators.maxLength(100)],
      }
    )
  }

  ngOnInit() {
    this.registedate = new Date();
    this.display = true;
    //日期格式转换为yyyy-mm-dd
    if(this.currentPer.birthday){
      this.currentPer.birthday = PUblicMethod.formateDateTime(this.currentPer.birthday);
    }
    if(this.currentPer.registedate){
      this.currentPer.registedate = PUblicMethod.formateDateTime(this.currentPer.registedate);
    }
    if(this.currentPer.validdate){
      this.currentPer.validdate = PUblicMethod.formateDateTime(this.currentPer.validdate);
    }
    this.minDate = new Date();
    this.maxDate = new Date();
    // console.log(this.currentPer);
    this.submitAddPerson[0].oid = this.currentPer.oid;
    this.submitUpdatePerson[0].oid = this.currentPer.oid;
    this.submitAddPerson[0].organization = this.currentPer.label;
    if(this.state ==='add') {
      this.title = '新增人员信息';
    }else {
      //图片赋初始值
      this.imgUrl_1 = this.currentPer.photo1;
      this.imgUrl_2 = this.currentPer.photo2;
      this.submitUpdatePerson[0].photo1 = this.currentPer.photo1;
      this.submitUpdatePerson[0].photo2 = this.currentPer.photo2;
      this.title = '修改人员信息';
    }
  }
  showAddInspectionPlanMask(){
    this.showAddPlanMask = !this.showAddPlanMask
  }
  //取消遮罩层
  closeAddPlanTreeMask(bool){
    this.showAddPlanMask = bool;
  }
  clearTreeDialog() {
    this.currentPer.label = ''
  }
  addPlanOrg(org){
    this.currentPer.oid = org[0].oid;
    this.currentPer.label = org[0].label
    // this.submitData.organs_names = [];
    // for(let i = 0;i<org.length;i++){
    //   this.submitData.organs_ids.push(org[i]['oid'])
    //   this.submitData.organs_names.push(org[i]['label'])
    // }
    // this.submitData.orggans_name =  this.submitData.organs_names.join(',');
    this.showAddPlanMask = false;
  }
  closePersonEditMask(bool){
    this.closePersonEdit.emit(bool);
  }

  //确定
  formSubmit(bool){
    if(this.state ==='add'){
      this.submitAddPerson[0].name = this.person.value.perName;
      this.submitAddPerson[0].pid = this.person.value.pid;
      this.submitAddPerson[0].pwd = this.person.value.pwd;
      this.submitAddPerson[0].mobile = this.person.value.mobile;
      this.submitAddPerson[0].addr = this.person.value.addr;
      this.submitAddPerson[0].sex = this.person.value.sex;
      this.submitAddPerson[0].birthday = this.person.value.birthday;
      this.submitAddPerson[0].registedate = this.person.value.dateGroup.registedate;
      this.submitAddPerson[0].validdate = this.person.value.dateGroup.validdate;
      this.submitAddPerson[0].organization = this.person.value.organization;
      this.submitAddPerson[0].post = this.person.value.post;
      this.submitAddPerson[0].tel = this.person.value.tel;
      this.submitAddPerson[0].email = this.person.value.email;
      this.submitAddPerson[0].idcard = this.person.value.idcard;
      this.submitAddPerson[0].wechat = this.person.value.wechat;
      this.submitAddPerson[0].remark1 = this.person.value.remark1;
      this.addPerson(bool);
    }else{
      this.submitUpdatePerson[0].name = this.person.value.perName;
      this.submitUpdatePerson[0].pid = this.person.value.pid;
      this.submitUpdatePerson[0].mobile = this.person.value.mobile;
      this.submitUpdatePerson[0].addr = this.person.value.addr;
      this.submitUpdatePerson[0].sex = this.person.value.sex;
      this.submitUpdatePerson[0].birthday = this.person.value.birthday;
      this.submitUpdatePerson[0].registedate = this.person.value.dateGroup.registedate;
      this.submitUpdatePerson[0].validdate = this.person.value.dateGroup.validdate;
      this.submitUpdatePerson[0].organization = this.person.value.organization;
      this.submitUpdatePerson[0].post = this.person.value.post;
      this.submitUpdatePerson[0].tel = this.person.value.tel;
      this.submitUpdatePerson[0].email = this.person.value.email;
      this.submitUpdatePerson[0].idcard = this.person.value.idcard;
      this.submitUpdatePerson[0].wechat = this.person.value.wechat;
      this.submitUpdatePerson[0].remark1 = this.person.value.remark1;
      this.updatePerson(bool);
    }
  }

  //新增人员
  addPerson(bool){
    this.systemService.addPerson(this.submitAddPerson).subscribe(()=>{
      this.addPer.emit(bool);
    },(err:Error)=>{
      let message ;
      if(JSON.parse(JSON.stringify(err)).status===504){
        message = '似乎网络出现了问题，稍后重试'
      }else{
        message =err
      }
      this.confirmationService.confirm({
        message: message,
        rejectVisible:false,
      })
    })
  }

  //修改人员
  updatePerson(bool){
    console.log(this.submitUpdatePerson[0]);
    this.systemService.updatePerson(this.submitUpdatePerson).subscribe(()=>{
      this.updatePer.emit(this.currentPer);
      this.closePersonEdit.emit(bool);
    })
  }

  //图片上传
  fileChange(event, num){
    let that = this;
    let file = event.target.files[0];
    let imgUrl = window.URL.createObjectURL(file);
    let sanitizerUrl = this.sanitizer.bypassSecurityTrustUrl(imgUrl);
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function(theFile) {
      if(num == 1){
        that.submitAddPerson[0].photo1 = theFile.target['result']  //base64编码,用一个变量存储
        that.submitUpdatePerson[0].photo1 = theFile.target['result']  //base64编码,用一个变量存储
      }else {
        that.submitAddPerson[0].photo2 = theFile.target['result']  //base64编码,用一个变量存储
        that.submitUpdatePerson[0].photo2 = theFile.target['result']  //base64编码,用一个变量存储
      }
    };
    if(num == 1){
      this.imgUrl_1 = sanitizerUrl;
    }else {
      this.imgUrl_2 = sanitizerUrl;
    }
  }

  //输入身份证，获取生日日期
  idcardChange(e){
    if(this.person.get('idcard').valid){
      let birthday = this.getBirthday(e.target.value);
      this.currentPer.birthday = birthday;
    }
  }

  //根据身份证获取生日日期
  getBirthday(psidno){
    var birthdayno,birthdaytemp
    if(psidno.length==18){
      birthdayno=psidno.substring(6,14)
    }else if(psidno.length==15){
      birthdaytemp=psidno.substring(6,12)
      birthdayno="19"+birthdaytemp
    }else{
      alert("错误的身份证号码，请核对！")
      return false
    }
    var birthday=birthdayno.substring(0,4)+"-"+birthdayno.substring(4,6)+"-"+birthdayno.substring(6,8)
    return birthday
  }

}
